Drupal.canvas_fields = {};

(function ($) {
	
  Drupal.behaviors.canvas_field = {
    attach: function(context, settings) {
    	
      $('input.drawing-board:not(".canvas-field-processed")', context).each(function(context) {

        var field_settings = settings.drawing_board[0];
        Drupal.canvas_fields[this.id] = new CanvasField(this, field_settings, this.id);
        $(this).addClass('canvas-field-processed');
        
        if($(this).val()) { 
          Drupal.canvas_fields[this.id].setImage($(this).val());
        }
      });

      Drupal.Nodejs.callbacks.drawingBoardCallBack = {
        callback: function (message) {
            var id = message.data.nid;
            var data = message.data.msg;
            if (data != ''){
              Drupal.canvas_fields[id].setImage(data);
            }
          }
      }
    }
  }

  CanvasField = function(selector, settings, id) {
    this.field = $(selector),
    this.canvas = $('<canvas id="drawCanvas' + id + '">');
    this.context = this.canvas[0].getContext("2d");
    this.state = 'inactive';
    this.settings = $.extend(true, {
      'default_tool' : 'Pen'
    }, settings); 

    this.render();
    
    return this;
  }
  
  CanvasField.prototype.render = function() {
    var output = $('<div class="canvas-outer-wrapper">');
    
    if (this.settings.style.height || this.settings.style.width) {
      //Resize canvas, not wrappers.
      this.resize(this.settings.style.height, this.settings.style.width);
    }
    var innerwrapper = $('<div class="canvas-inner-wrapper">').css(this.settings.style);
    innerwrapper.append(this.canvas);
    output.append(innerwrapper);
    this.field.after(output);
  }

  CanvasField.prototype.resize = function(height, width) {
    this.canvas.attr('height', height).attr('width', width);
  }

  CanvasField.prototype.setImage = function(data) {
    var self = this;
    var img = new Image();
    img.src = data;
    img.onload = function() {
//      self.resize(img.height, img.width);
    	self.context.clearRect(0, 0, self.settings.style.width, self.settings.style.height);
      self.context.drawImage(img, 0, 0);
    }
  }

})(jQuery);

